<template>
  <div class="main">
    <div class="input" v-if="showSuccess === false && showError === false && pay.PayUrl">
      <vue-qr
        :size="400"
        :text="pay.PayUrl"
        :auto-color="true"
      />
      <div class="ercode-text">充值金额:{{store.state.AddCreditQuery.Amount}}元</div>
    </div>
    <div class="input" v-if="showSuccess">
      <i class="el-icon-check success"></i>
      <div class="ercode-text">充值成功, 即将返回上一页</div>
    </div>
    <div class="input" v-if="showError">
      <i class="el-icon-close success"></i>
      <div class="ercode-text">充值失败, 请联系工作人员</div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import ReservationMixin from '@/mixins/reservation'
import { GetPayResult, GetQrCode, InspectionPayAndSign } from './apis/inspection'
import { IPayAndSignQuery, IReservationInspection, ISysPay } from './interface/inspection'
import VueQr from 'vue-qr'
import { GetUser } from '@/apis/api'

@Component({
  components: {
    VueQr
  }
})
export default class InspectionPay extends mixins(ReservationMixin) {
  private amount = 0
  private pay : ISysPay | any = {}
  private showSuccess = false
  private showError = false

  private async created () {
    this.setTip('请扫码支付')
    this.setMaxTime(120)
    this.updateTimeHandler('back')
    this.getQrCode()
  }

  private async getQrCode () {
    try {
      this.showLoading('正在获取门诊充值二维码')
      const result = await GetQrCode(this.store.state.AddCreditQuery)
      if (result.data?.Code === 200) {
        this.hideLoading()
        this.store.state.AddCreditPay = result.data.Data
        this.pay = result.data.Data
        this.getPayResult()
      } else {
        this.showLoading('获取门诊充值二维码失败')
        const handler = window.setTimeout(() => {
          this.hideLoading()
        }, 3000)
        this.handlers.push(handler)
        this.logger.warning(`获取门诊充值二维码失败${JSON.stringify(result)}`)
      }
    } catch (error) {
      this.logger.error(`获取门诊充值二维码异常:${error}`)
    }
  }

  private async getPayResult () {
    try {
      const result = await GetPayResult(this.pay.ID)
      if (result.data?.Code === 200) {
        if (result.data.Data.PayStatus === '支付成功' && result.data.Data.UseStatus === '成功') {
          if (this.store.state.Inspection) {
            this.sign(this.store.state.Inspection)
          }
          if (this.store.state.patient) {
            const result = await GetUser(this.store.state.patient)
            if (result.data?.Code === 200) {
              this.store.commit('updatePatient', result.data.Data)
            }
            this.setTime(5)
          }
          this.showSuccess = true
          return
        }
        if (result.data.Data.PayStatus === '支付成功' && result.data.Data.UseStatus === '失败') {
          this.showError = true
          return
        }
      } else {
        this.logger.warning('获取支付结果失败')
      }
    } catch (error) {
      this.logger.error(`获取支付结果失败:${error}`)
    }
    const handler = window.setTimeout(() => {
      this.getPayResult()
    }, 1000)
    this.handlers.push(handler)
  }

  private busy = false
  /**
   * 签到
   */
  private async sign (element: IReservationInspection) {
    try {
      if (this.busy) return
      this.busy = true
      this.showLoading('数据处理中...')
      this.logger.info('开始签到')
      if (!this.store.state.room || !this.store.state.room.HisId) {
        this.logger.warning('签到失败, 无效的诊室信息')
        this.$messageBox.show({ content: '无效的诊室信息' })
        return
      }
      if (!this.store.state.patient || !this.store.state.patient.CardNo) {
        this.logger.warning('签到失败, 无效的诊室信息')
        this.$messageBox.show({ content: '无效的诊室信息' })
        return
      }
      const query : IPayAndSignQuery = {
        RoomId: this.store.state.room.HisId,
        CardNo: this.store.state.patient.CardNo,
        ApplyNo: element.applyNo
      }
      const result = await InspectionPayAndSign(query)
      this.hideLoading()
      this.store.state.Inspection = undefined
      this.busy = false
      if (result.data.Code === 200) {
        this.logger.info(`签到成功, 返回信息:${JSON.stringify(result.data)}`)
        this.$messageBox.show({
          content: '签到成功',
          confirm: () => {
            this.back()
          },
          duration: 10,
          confirmText: '返回',
          cancelText: '退出',
          cancel: () => {
            this.home()
          }
        })
      } else {
        this.logger.warning(`签到失败, 返回信息:${JSON.stringify(result.data)}`)
        this.$messageBox.show({ content: result.data.Message.substring(0, 30) })
      }
    } catch (error) {
      this.$messageBox.show({ content: '签到失败, 请稍后重试' })
      this.logger.warning(`签到异常:${error}`)
    }
  }
}
</script>
<style>
  .el-button--primary {
      color: #FFF !important;
      background-color: #409EFF !important;
      border-color: #409EFF !important;
  }
  .el-button{
    border-radius: 0 4px 4px 0;
  }
</style>

<style scoped>
  .main {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    height: 100%;
    align-items: center;
  }
  .input{
    width: 50%;
  }
  .ercode-text{
    font-size: 2.5rem;
    font-weight: bold;
    margin: 1rem 0;
  }
  .success{
    font-size: 10rem;
    color:darkkhaki;
  }
</style>
